import mapboxgl from 'mapbox-gl';
import layerControl from '@/js/mapbox-gl/mapbox-gl-layer';
mapboxgl.accessToken = 'pk.eyJ1Ijoia3VnZWxpZ3VpIiwiYSI6ImNpdmxzNHhndDAwYnUydG93N3ZvcGtzdzcifQ.3NiK4xN3A1yodHsGmQHofg';
import * as turf from '@turf/turf'
import axios from 'axios';
const parcelLayerId = 'allparcel', parcelSourceLayer = 'parcel';
var opts;
class YTMap {
    constructor(_opts) {
        var map = this.initMap(_opts);
        map.once('load', () => {
            map.resize();
            this.addControl();
            if (_opts.load) {
                _opts.load(map);
            }
        })
        opts = _opts;
        this.map = map;
    }
    initMap(opts) {
        const villageSourceId = 'yitugis';
        this.villageSourceId = villageSourceId;
        // TODO 这里请换成自己的地址，文件在public/fonts中
        var glyphsHref = "http://192.9.102.124:8207/mapbox/fonts/{fontstack}/{range}.pbf";
        var map = new mapboxgl.Map({
            container: opts.map,
            minZoom: 14,
            maxZoom: 18,
            style: {
                "version": 8,
                "name": "yitu",
                "zoom": 11,
                "glyphs": glyphsHref,
                "layers": [],
                "sources": {}
            },
            center: [113.842105479, 22.574724395], // starting position
            zoom: 16 // starting zoom
        });
        map.on('load', () => {
            this.addTiandituLayer(map);
            this.addVillageLayer(map);
            this.addParcelLayer(map);
        });
        this._map = map;
        return map;
    }
    addTiandituLayer(map) {
        var subdomains = '01234567', tk = '0936715ab810df3a3bc32d22ab83edd9';
        var vecSourceUrl = [], cvaSourceUrl = [], imgSourceUrl = [];
        var tdtUrlFormat = 'https://t{s}.tianditu.gov.cn/DataServer?T={style}_w&x={x}&y={y}&l={z}&tk=' + tk;
        for (var i = 0; i < subdomains.length; i++) {
            vecSourceUrl.push(tdtUrlFormat.replace('{s}', i).replace('{style}', 'vec'));
            cvaSourceUrl.push(tdtUrlFormat.replace('{s}', i).replace('{style}', 'cva'));
            imgSourceUrl.push(tdtUrlFormat.replace('{s}', i).replace('{style}', 'img'));
        }
        map.addSource("tiandit_vec", {
            "type": "raster",
            "tileSize": 256,
            "minzoom": 10,
            "maxzoom": 18,
            "tiles": vecSourceUrl
        });
        map.addSource("tiandit_cva", {
            "type": "raster",
            "tileSize": 256,
            "minzoom": 10,
            "maxzoom": 18,
            "tiles": cvaSourceUrl
        });
        map.addSource("tiandit_img", {
            "type": "raster",
            "tileSize": 256,
            "minzoom": 10,
            "maxzoom": 18,
            "tiles": imgSourceUrl
        });
        let layersConf = [
            {
                "id": "tiandit_vec",
                "source": "tiandit_vec",
                "type": "raster"
            },
            {
                "id": "tiandit_img",
                "source": "tiandit_img",
                "type": "raster",
                "layout": {
                    "visibility": "none"
                }
            },
            {
                "id": "tiandit_cva",
                "source": "tiandit_cva",
                "type": "raster"
            }];
        layersConf.forEach(conf => {
            map.addLayer(conf);
        });
    }
    // 添加物业区域图层
    addVillageLayer(map) {
        const villageLayerId = 'village', villageSourceId = 'village';
        // TODO 这里调接口请求getFeatureCollection获取已落图物业区域
        // get请求
        axios.get("http://192.9.102.124:8207/mapbox/json/wxj-village.json").then(res => {
            map.addSource(villageSourceId, {
                type: 'geojson',
                data: res.data
            });
            //初步落图
            map.addLayer({
                "minzoom": 10,
                "maxzoom": 19,
                "id": villageLayerId + "_1",
                "source": villageSourceId,
                "type": "fill",
                "filter": ['==', 'type', 1],
                "paint": {
                    "fill-color": "#ddd206",
                    "fill-opacity": 0.5,
                },
                "layout": {
                    "visibility": "visible"
                }
            });
            //二次确认
            map.addLayer({
                "minzoom": 10,
                "maxzoom": 19,
                "id": villageLayerId + "_2",
                "source": villageSourceId,
                "type": "fill",
                "filter": ['==', 'type', 2],
                "paint": {
                    "fill-color": '#21dd00',
                    "fill-opacity": 0.5,
                },
                "layout": {
                    "visibility": "visible"
                }
            });

            map.on('click', villageLayerId + "_1", (e) => { this.villageLayerClick(map, e); });
            map.on('click', villageLayerId + "_2", (e) => { this.villageLayerClick(map, e); });

            map.addLayer({
                "minzoom": 10,
                "maxzoom": 19,
                "id": villageLayerId + "_line",
                "source": villageSourceId,
                "type": "line",
                "paint": {
                    "line-color": '#00E5EE',
                    "line-width": 1,
                    "line-opacity": 0.7,
                },
                "layout": {
                    "visibility": "visible"
                }
            });

            if (this.layerControl) {
                this.layerControl.changeLayer('已落图物业区域', true);
            }

            var features = [];
            res.data.features.forEach(item => {
                item.properties.name = item.properties.name ? item.properties.name : '-';
                if (item.geometry.type == 'MultiPolygon') {
                    item.geometry.coordinates.forEach(coordinate => {
                        var feature = turf.center({ 'type': 'Polygon', coordinates: coordinate });
                        feature.properties = item.properties;
                        features.push(feature);
                    })
                } else {
                    var feature = turf.center(item);
                    feature.properties = item.properties;
                    features.push(feature);
                }
            });
            let centerSourceId = villageSourceId + "_text";
            map.addSource(centerSourceId, {
                type: 'geojson',
                data: {
                    "type": "FeatureCollection", "features": features
                }
            });
            map.addLayer({
                "id": centerSourceId,
                "minzoom": 15,
                "maxzoom": 19,
                "source": centerSourceId,
                "type": "symbol",
                "layout": {
                    "text-field": "{name}",
                    "text-size": 12,
                    "text-allow-overlap": true
                }
            });
        });
    }
    // 物业区域图层点击
    villageLayerClick(map, e) {
        let html = '', index = 1;
        e.features.forEach(item => {
            let name = item.properties.name;
            name = (name == null || name == 'null') ? '物业项目区域名称为空' : name;
            html += (index++) + '、' + name + '<br/>';
        })
        if (this.popup && !this.popup.isOpen()) {
            this.popup.remove();
            this.popup = null;
        }
        if (!this.popup) {
            this.popup = new mapboxgl.Popup({ closeOnClick: false, className: 'popup-list' })
                .setLngLat(e.lngLat)
                .addTo(map);
        }
        this.popup.setLngLat(e.lngLat).setHTML(html);
    }
    // 添加宗地图层
    addParcelLayer(map) {
        map = map ? map : this._map;
        // TODO 这里请改成对应的地址
        map.addSource(parcelLayerId, {
            "type": "vector",
            "tiles": ["http://localhost/tiles/parcel/{z}/{x}/{y}.mvt"]
            // "tiles": ["http://192.9.102.125:8100/wxj/wmts?REQUEST=GetTile&SERVICE=WMTS&VERSION=1.0.0&LAYER=wxj:parcel&STYLE=&TILEMATRIX=EPSG:900913:{z}&TILEMATRIXSET=EPSG:900913&FORMAT=application/vnd.mapbox-vector-tile&TILECOL={x}&TILEROW={y}"]
        });
        let layersConf = [
            {
                "id": parcelLayerId,
                "source": parcelLayerId,
                "type": "fill",
                "source-layer": parcelSourceLayer,
                "paint": {
                    "fill-color": "#E9FFBE",
                    "fill-opacity": 0.8,
                    "fill-outline-color": "#38AA00"
                },
                "layout": {
                    "visibility": "none"
                }
            },
            {
                "id": parcelLayerId + "_text",
                "source": parcelLayerId,
                "type": "symbol",
                "source-layer": parcelSourceLayer,
                "minzoom": 15,
                "paint": {

                },
                "layout": {
                    "visibility": "none",
                    "text-field": "{PARCEL_NO}",
                    "text-size": 12
                }
            }];
        layersConf.forEach(conf => {
            map.addLayer(conf);
        });
        map.on('click', parcelLayerId, (e) => { this.parcelLayerClick(map, e); });
    }
    // 宗地图层点击事件
    parcelLayerClick(map, e) {
        map = map ? map : this._map;
        var highlightIds = [];
        e.features.forEach(item => {
            highlightIds.push(item.properties.OBJECTID);
            if (opts.parcelClick) {
                opts.parcelClick(item.properties);
            }
        })
        // 点击的高亮
        this.highlightParcelLayer(map, highlightIds);
    }
    highlightParcelLayer(map, highlightIds) {
        map = map ? map : this._map;
        let highlightLayerId = parcelLayerId + "_highlight";
        if (map.getLayer(highlightLayerId)) {
            map.removeLayer(highlightLayerId);
        }
        if (highlightIds) {
            map.addLayer({
                "id": highlightLayerId,
                "source": parcelLayerId,
                "type": "line",
                "source-layer": parcelSourceLayer,
                filter: ['in', 'OBJECTID', ...highlightIds],
                "paint": {
                    "line-color": "#ff0000",
                    "line-width": 2
                }
            });
        }
    }
    // 添加控件
    addControl() {
        var map = this._map;
        // 添加版权控件
        map.addControl(new mapboxgl.AttributionControl({
            customAttribution: '©天地图 - GS(2022)3124号'
        }), 'bottom-left');
        // 添加导航空间
        map.addControl(new mapboxgl.NavigationControl(), 'bottom-right');
        // 添加比例尺控件
        var scale = new mapboxgl.ScaleControl({
            maxWidth: 80,
            unit: 'metric'
        });
        map.addControl(scale);

        var baselayers = {
            "标准": {
                className: 'nomarl',
                layer: 'tiandit_vec'
            },
            "影像": {
                className: 'satellite',
                layer: 'tiandit_img'
            }
        };
        var overlays = {
            "地名标注": 'tiandit_cva',
            "已落图物业区域": ['village_1', 'village_2', 'village_line', 'village_text'],
            "宗地": [parcelLayerId, parcelLayerId + '_text']
        }
        this.layerControl = new layerControl(baselayers, overlays);
        // 添加图层控制控件
        map.addControl(this.layerControl, 'top-right');
    }
    hilightVillage(villageId) {
        var map = this._map;
        const layerId = 'hilightVillage';
        if (map.getLayer(layerId)) {
            map.removeLayer(layerId);
        }
        if (!villageId) {
            return;
        }
        map.addLayer({
            "id": layerId,
            "source": this.villageSourceId,
            "source-layer": "village",
            "type": "line",
            "minzoom": 14,
            "maxzoom": 18,
            "paint": {
                "line-color": 'red',
                "line-width": 5,
                "line-opacity": 1,
            },
            "filter": ["==", 'id', villageId],
            "layout": {
                "visibility": "visible"
            }
        });
    }
}

export default YTMap;